package com.liuyang.concurrency.chapter10;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeoutException;

public class BooleanLock implements Lock{

    //true 代表获取到
    //false 没锁，线程可以获取
    private boolean initValue;

    private Thread currentThread;

    private Collection<Thread> blockThreadCollection = new ArrayList<>();

    public BooleanLock() {
        this.initValue =false;
    }

    @Override
    public synchronized void lock() throws InterruptedException {
        while (initValue){
            //添加进阻塞队列
            blockThreadCollection.add(Thread.currentThread());
            this.wait();
        }
        blockThreadCollection.remove(Thread.currentThread());
        this.initValue = true;
        currentThread = Thread.currentThread();
    }

    @Override
    public synchronized void lock(long mills) throws InterruptedException, TimeoutException {
        if(mills<=0){
            lock();
        }

        long hasRemind = mills;
        long endTime = System.currentTimeMillis()+mills;
        while (initValue){
            if(hasRemind <= 0){
                throw new TimeoutException("time out");
            }
            blockThreadCollection.add(Thread.currentThread());
            this.wait(mills);
            hasRemind = endTime -System.currentTimeMillis();

        }
        this.initValue = true;
        currentThread = Thread.currentThread();

    }

    @Override
    public synchronized void unlock() {
        if(currentThread == Thread.currentThread()){
            this.initValue = false;
            System.out.println(Thread.currentThread().getName()+" released the lock monitor...");
            this.notifyAll();
        }else{
            System.out.println("you havenot auth release the lock");
        }

    }

    @Override
    public Collection<Thread> getBlockedThread() {
        return Collections.unmodifiableCollection(blockThreadCollection);
    }

    @Override
    public int getBlockedSize() {
        return blockThreadCollection.size();
    }
}

